package com.gpagers.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.index.Fields;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gpagers.kit.lucene.FieldType;
import com.gpagers.kit.lucene.IndexFiles;
import com.gpagers.kit.lucene.SearchFiles;
import com.gpagers.kit.lucene.util.ResultEntity;
import com.gpagers.tools.AjaxBean;
import com.gpagers.tools.GlobalConfigHolder;
import com.gpagers.tools.ResultType;

@Controller
public class LuceneController extends BaseController{

	@RequestMapping(value = "createIndex")
	@ResponseBody
	public String createIndex(HttpServletRequest request,
			HttpServletResponse response) {    
		IndexFiles indexFiles = new IndexFiles();
		AjaxBean ab = new AjaxBean();
		try {
			indexFiles.createIndex(
					GlobalConfigHolder.getProperty("indexPath"),
					GlobalConfigHolder.getProperty("docPath"));
		} catch ( Exception e ) {
			ab.setResult(ResultType.错误);
			ab.setReason(e.toString());
			return JSON.toJSONString(ab);
		}
		ab.setResult(ResultType.成功);
		return JSON.toJSONString(ab);
	}
	
	@RequestMapping(value = "searchKey")
	@ResponseBody
	public String searchKey(HttpServletRequest request,
			HttpServletResponse response) {  
		String key = request.getParameter("key");
		SearchFiles sf = new SearchFiles();
		AjaxBean ab = new AjaxBean();
		List< ResultEntity > list;
		try {
			list = sf.searchFile(key, FieldType.内容,FieldType.名字);
		} catch ( Exception e ) {
			ab.setResult(ResultType.错误);
			ab.setReason(e.toString());
			return JSON.toJSONString(ab);
		}
		return JSONArray.toJSONString(list,
			    SerializerFeature.DisableCircularReferenceDetect);
	}
}
